<template>
  <div class="cart-container">
    <!-- 头部操作区域 -->
    <el-card class="header-card">
      <div class="header-title">我的购物车</div>
    </el-card>

    <el-card v-if="cartItems.length > 0" class="cart-list-card">
      <el-table
        :data="cartItems"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="name" label="商品名称" min-width="200" />
        
        <el-table-column label="规格" min-width="200">
          <template #default="scope">
            <div class="spec-text">{{ scope.row.spec }}</div>
          </template>
        </el-table-column>
        
        <el-table-column prop="price" label="单价" width="100" align="right">
          <template #default="scope">
            {{ scope.row.price }} 元
          </template>
        </el-table-column>
        
        <el-table-column label="数量" width="120" align="center">
          <template #default="scope">
            <el-input-number 
              v-model="scope.row.count" 
              :min="1" 
              :max="10" 
              :step="1"
              @change="updateCartItem(scope.row)"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="totalPrice" label="小计" width="120" align="right">
          <template #default="scope">
            {{ scope.row.totalPrice }} 元
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="80" align="center">
          <template #default="scope">
            <el-button 
              type="danger" 
              size="mini"
              @click="removeFromCart(scope.row)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="cart-summary" style="margin-top: 20px; text-align: right">
        <span style="font-size: 16px; font-weight: bold">总计: {{ totalPrice }} 元</span>
        <el-button type="primary" style="margin-left: 20px">去结算</el-button>
      </div>
    </el-card>

    <el-card v-else class="empty-cart-card">
      <div class="empty-cart-content">
        <el-icon class="empty-icon"><ShoppingCart /></el-icon>
        <div class="empty-text">购物车还是空的，快去挑选喜欢的菜品吧</div>
        <el-button type="primary" @click="goToDishPage">去选菜</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ShoppingCart } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'

// 购物车数据
const cartItems = ref([])
const totalPrice = ref(0)
const router = useRouter()
const route = useRoute()

// 生命周期
onMounted(() => {
  // 检查路由状态中是否有新增商品
  checkAddedItem()
  
  // 监听路由变化，获取最新传递的商品数据
  watch(() => route, () => {
    checkAddedItem()
  })
})

// 检查路由状态中是否有新增商品
const checkAddedItem = () => {
  const { addedItem, isNewAdd } = route.state || {}
  if (isNewAdd && addedItem) {
    addItemToCart(addedItem)
    
    // 清除路由状态，避免重复添加
    history.replaceState({}, document.title)
  }
}

// 添加商品到购物车
const addItemToCart = (item) => {
  // 检查是否已存在相同规格的商品
  const existingIndex = cartItems.value.findIndex(existingItem => 
    existingItem.id === item.id && 
    existingItem.sugar === item.sugar && 
    existingItem.temp === item.temp && 
    JSON.stringify(existingItem.topping) === JSON.stringify(item.topping)
  )
  
  if (existingIndex >= 0) {
    // 已存在则增加数量
    cartItems.value[existingIndex].count += item.count
    cartItems.value[existingIndex].totalPrice = (cartItems.value[existingIndex].price * cartItems.value[existingIndex].count).toFixed(2)
  } else {
    // 不存在则添加新商品
    cartItems.value.push({
      ...item,
      totalPrice: (item.price * item.count).toFixed(2)
    })
  }
  
  updateTotalPrice()
}

// 更新购物车单项
const updateCartItem = (item) => {
  const index = cartItems.value.findIndex(i => 
    i.id === item.id && 
    i.sugar === item.sugar && 
    i.temp === item.temp && 
    JSON.stringify(i.topping) === JSON.stringify(item.topping)
  )
  
  if (index >= 0) {
    cartItems.value[index].count = item.count
    cartItems.value[index].totalPrice = (item.price * item.count).toFixed(2)
    updateTotalPrice()
  }
}

// 从购物车移除
const removeFromCart = (item) => {
  cartItems.value = cartItems.value.filter(i => 
    !(i.id === item.id && 
      i.sugar === item.sugar && 
      i.temp === item.temp && 
      JSON.stringify(i.topping) === JSON.stringify(item.topping))
  )
  updateTotalPrice()
  ElMessage.success('已移除')
}

// 更新总计价格
const updateTotalPrice = () => {
  totalPrice.value = cartItems.value.reduce((sum, item) => {
    return sum + (parseFloat(item.price) * item.count)
  }, 0).toFixed(2)
}

// 前往菜品页面
const goToDishPage = () => {
  router.push('/center/dish')
}
</script>

<style scoped>
.cart-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
}

.cart-list-card {
  padding: 20px;
}

.empty-cart-card {
  padding: 40px;
  text-align: center;
}

.empty-icon {
  font-size: 60px;
  color: #909399;
  margin-bottom: 20px;
}

.empty-text {
  font-size: 16px;
  color: #909399;
  margin-bottom: 20px;
}

.spec-text {
  font-size: 14px;
  color: #606266;
}

.cart-summary {
  padding: 10px 0;
  border-top: 1px solid #ebeef5;
  margin-top: 15px;
}
</style>